<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\LoginRequest;
use App\Jobs\Auth\Login;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    /**
     * Login
     *
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function login(LoginRequest $request)
    {
        $account = $this->dispatchNow(new Login($request));

        Auth::login($account);

        $token = JWTAuth::fromUser($account);

        return $this->response->item($account, new UserTransformer())->addMeta('token', $token);
    }

    /**
     * Logout
     *
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function logout()
    {
        if (Auth::check()) {
            Auth::logout();
        }

        $token = trim(str_ireplace('Bearer', '', request()->header('Authorization', request()->get('token'))));

        JWTAuth::invalidate($token);

        return $this->response->noContent();
    }

    /**
     * @author Vance
     *
     * @return \Dingo\Api\Http\Response
     */
    public function profile()
    {
        return $this->response->item($this->user, new UserTransformer());
    }

    /**
     * Change password
     *
     * @author Eddie
     *
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     */
    public function changePwd(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'old_password' => 'required',
            'new_password' => 'required|min:6|max:20',
        ], [
            'old_password.required' => '请输入旧密码',
            'new_password.required' => '请输入新密码',
            'new_password.min'      => '密码长度不小于6位',
            'new_password.max'      => '密码长度不大于20位',
        ]);

        if ($validator->fails()) {
            return $this->response->error($validator->errors()->first(), 422);
        }

        $user = $this->user();
        if (!Hash::check($request->old_password, $user->password)) {
            return $this->response->error('旧密码错误', 422);
        }

        $user->password = Hash::make($request->new_password);
        $user->save();

        return $this->response->noContent();
    }
}
